import 'dart:async';

import 'package:flutter/material.dart';
import 'package:tender_flutter/constant/api_path.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:webview_flutter/webview_flutter.dart';

class ProtocolPage extends StatefulWidget {
  /// 协议类型 参见 AppConstant
  final int protocolType;

  const ProtocolPage({Key key, this.protocolType}) : super(key: key);

  @override
  _ProtocolPageState createState() => _ProtocolPageState();
}

class _ProtocolPageState extends State<ProtocolPage> {
  final Completer<WebViewController> _controller =
      Completer<WebViewController>();
  bool isLoading = true; // 设置状态

  @override
  void initState() {
    super.initState();
    // if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _initAppBar(),
      body: _initBody(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text(_getProtocolTitle(), style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
    );
  }

  /// 内容体
  Widget _initBody() {
    return Stack(
      children: [
        WebView(
          initialUrl: _getProtocolUrl(),
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _controller.complete(webViewController);
          },
          navigationDelegate: (NavigationRequest request) {
            var url = request.url;
            print("visit $url");
            setState(() {
              isLoading = true; // 开始访问页面，更新状态
            });

            return NavigationDecision.navigate;
          },
          onPageFinished: (String url) {
            setState(() {
              isLoading = false; // 页面加载完成，更新状态
            });
          },
        ),
        isLoading
            ? Container(
                child: Center(
                  child: CircularProgressIndicator(),
                ),
              )
            : Container(),
      ],
    );
  }

  String _getProtocolUrl() {
    switch (widget.protocolType) {
      case AppConstant.PROTOCOL_USER:
        return ApiPath.url_service;
        break;
      case AppConstant.PROTOCOL_PRIVACY:
        return ApiPath.url_privacy;
        break;
    }
    return "";
  }

  String _getProtocolTitle() {
    switch (widget.protocolType) {
      case AppConstant.PROTOCOL_USER:
        return "用户服务协议";
        break;
      case AppConstant.PROTOCOL_PRIVACY:
        return "用户隐私政策";
        break;
      default:
        return "";
        break;
    }
  }
}
